<template>
	<div ref="threeContainer" class="model-content"></div>
</template>

<script>
	import * as THREE from "three";
	import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader.js";
	import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";
	import {getModelDetail} from '@/api/model.js';
	import watermark from '@/assets/js/watermark.js'
	export default {
		props: {
			modelUrl:{
				type: String,
				default: ""
			}
		},

		data() {
			return {
				camera: null,
				scene: null,
				renderer: null
			}
		},
		
		mounted(){
			watermark.set("云图 3D",this.$refs.threeContainer);
		},
		
		beforeDestroy() {
			watermark.set("",this.$refs.threeContainer);
		},
		
		methods: {
			initModel(){
				const width = this.$refs.threeContainer.clientWidth;
				const height = this.$refs.threeContainer.clientHeight;
				// 创建场景
				this.scene = new THREE.Scene();
				// 添加相机
				this.camera = new THREE.PerspectiveCamera(75, width / height, 0.01, 3000);
				this.camera.position.z = 1;
				this.camera.lookAt(0, 0, 0)
				// 创建渲染器
				this.renderer = new THREE.WebGLRenderer({ antialias: true,alpha:true });
				this.renderer.setSize(width, height);
				this.renderer.setClearColor(0x000000,0);
				this.$refs.threeContainer.appendChild(this.renderer.domElement);
				const loader = new GLTFLoader();				// 加载3D模型
				loader.load(this.modelUrl, (gltf) => {
					gltf.scene.traverse(function(child) {
						if (child.isMesh) {
							child.material.emissive = child.material.color;
							child.material.emissiveMap = child.material.map;
						}
					});
					this.scene.add(gltf.scene);
				},
				(xhr) =>{
					// console.log((xhr.loaded / xhr.total) * 100 + "% loaded");
				},
				(error) => {
					console.error(error);
				})	
				//添加控制器
				let controls = new OrbitControls(this.camera, this.renderer.domElement);
				controls.addEventListener("change", () => {
					this.renderer.render(this.scene, this.camera);
				});
			},
			
			animate(){
				requestAnimationFrame(this.animate);
				this.renderer.render(this.scene, this.camera);
			}
		},
		
		watch:{
			modelUrl:{
				handler:function(newV,oldV){
					if(newV){
						this.initModel();
						this.animate();
					}
				},
				deep:true,
				immediate:true
			}
		}
	};
</script>

<style lang="scss" scoped>
	.model-content{
		position: relative;
		width: 100%;
		height:100%;
	}
</style>
